package xxy.com.yangproject.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import xxy.com.yangproject.R;

/**
 * Created by xxy on 2018/8/5.
 *
 */

public class MyClipAndMatrix extends View {
    private int height;
    private int width;
    private int centerY;
    private int centerX;
    private Bitmap bitmap;
    private Paint paint;
    private Camera camera;
    private int offsetx;
    private int offsety;

    public MyClipAndMatrix(Context context) {
        super(context);
        init();
    }

    public MyClipAndMatrix(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyClipAndMatrix(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //paint
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);

        //得到屏幕中心的坐标
        DisplayMetrics dm = getResources().getDisplayMetrics();
        height = dm.heightPixels;
        width = dm.widthPixels;

        //得到一张图片
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.backgroud);
        offsetx = bitmap.getWidth() / 2;
        offsety = bitmap.getHeight() / 2;
        //屏幕中心点减去图片的半宽和半高
        centerY =height / 2 - offsety ;
        centerX = width / 2 - offsetx;

        //相机
        camera = new Camera();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        canvas.clipRect(centerX - 200, centerY - 200, centerX + 200, centerY + 200);
        canvas.save();
        camera.save();
        camera.rotateX(60);
        //如果你需要图形左右对称，需要配合上 Canvas.translate()，在三维旋转之前把绘制内容的中心点移动到原点，即旋转的轴心，然后在三维旋转后再把投影移动回来
        //Canvas 的几何变换顺序是反的，所以要把移动到中心的代码写在下面，把从中心移动回来的代码写在上面
        canvas.translate(centerX + offsetx, centerY + offsety);
        camera.applyToCanvas(canvas);
        //投影之前转移到原点，这个view在父布局中的原点是屏幕左上角
        canvas.translate(- centerX  - offsetx, -centerY - offsety);
        camera.restore();

        canvas.drawBitmap(bitmap, centerX, centerY, paint);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
    }
}
